package com.wenx.v3system.modular.platform.controller;

import cn.hutool.core.util.StrUtil;
import com.wenx.v3core.response.R;

import com.wenx.v3secure.annotation.Anonymous;
import com.wenx.v3system.modular.platform.domain.dto.PlatformLoginResult;
import com.wenx.v3system.modular.platform.domain.dto.LoginRequest;
import com.wenx.v3system.modular.platform.domain.dto.PlatformUserDto;
import com.wenx.v3system.modular.platform.domain.dto.RefreshTokenRequest;
import com.wenx.v3system.modular.platform.service.PlatformAuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;

/**
 * 平台认证控制器
 * 不再自签发平台JWT，统一委派至 v3-auth（OAuth2 授权服务器）
 *
 * @author wenx
 */
@Slf4j
@RestController
@RequestMapping("/api/v3/platform/auth")
@RequiredArgsConstructor
@Validated
@Tag(name = "平台认证", description = "平台用户认证相关接口")
@Anonymous
public class PlatformAuthController {

    private final PlatformAuthService platformAuthService;

    /**
     * 平台用户登录（委派至 v3-auth）
     */
    @PostMapping("/login")
    @Operation(summary = "平台用户登录", description = "使用用户名密码登录平台（委派至统一认证）")
    public R login(@Valid @RequestBody LoginRequest request) {
        PlatformLoginResult result = platformAuthService.login(request.getUsername(), request.getPassword());
        return R.ok(result);
    }

    /**
     * 平台用户登出（委派至 v3-auth 撤销令牌）
     */
    @PostMapping("/logout")
    @Operation(summary = "平台用户登出", description = "撤销访问令牌（委派至统一认证）")
    public R logout(@RequestHeader("Authorization") String authorization) {
        String token = extractToken(authorization);
        platformAuthService.logout(token);
        return R.ok("登出成功");
    }

    /**
     * 刷新Token（委派至 v3-auth）
     */
    @PostMapping("/refresh")
    @Operation(summary = "刷新Token", description = "使用刷新Token获取新的访问Token（委派至统一认证）")
    public R refreshToken(@Valid @RequestBody RefreshTokenRequest request) {
        PlatformLoginResult result = platformAuthService.refreshToken(request.getRefreshToken());
        return R.ok(result);
    }

    /**
     * 获取当前用户信息（委派至 v3-auth）
     * 返回完整的用户信息，包括角色、权限和菜单信息
     */
    @GetMapping("/current-user")
    @Operation(summary = "获取当前用户信息", description = "根据token获取当前用户信息，包含角色、权限和菜单信息（委派至统一认证）")
    public R getCurrentUser(@RequestHeader("Authorization") String authorization) {
        String token = extractToken(authorization);
        PlatformUserDto userDto = platformAuthService.validateToken(token);
        if (userDto == null) {
            return R.failed("用户验证失败");
        }
        
        // 构建完整的用户信息响应
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("user", userDto);
        userInfo.put("roles", userDto.getRoleCodes());
        userInfo.put("permissions", userDto.getPermissions());
        userInfo.put("menuCodes", userDto.getMenuCodes());
        userInfo.put("isSuperAdmin", userDto.getIsSuperAdmin());
        
        return R.ok(userInfo);
    }

    /**
     * 检查权限
     */
    @GetMapping("/check-permission")
    @Operation(summary = "检查权限", description = "检查当前用户是否有指定权限（统一认证）")
    public R checkPermission(
            @RequestHeader("Authorization") String authorization,
            @Parameter(description = "权限代码") @RequestParam @NotBlank String permission) {
        String token = extractToken(authorization);
        boolean hasPermission = platformAuthService.hasPermissionByToken(token, permission);
        return R.ok(hasPermission);
    }

    /**
     * 检查菜单权限
     */
    @GetMapping("/check-menu")
    @Operation(summary = "检查菜单权限", description = "检查当前用户是否有指定菜单权限（统一认证）")
    public R checkMenuPermission(
            @RequestHeader("Authorization") String authorization,
            @Parameter(description = "菜单代码") @RequestParam @NotBlank String menuCode) {
        String token = extractToken(authorization);
        boolean hasPermission = platformAuthService.hasMenuPermissionByToken(token, menuCode);
        return R.ok(hasPermission);
    }

    /**
     * 从Authorization头中提取Token
     */
    private String extractToken(String authorization) {
        if (StrUtil.isBlank(authorization) || !authorization.startsWith("Bearer ")) {
            throw new RuntimeException("无效的Authorization头");
        }
        return authorization.substring(7);
    }



}